import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpServletRequest;

import java.util.logging.Logger;

@WebListener
public class RequestLogListener implements ServletRequestListener {

    private static final Logger logger = Logger.getLogger(RequestLogListener.class.getName());
    private long startTime;

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        startTime = System.currentTimeMillis();
        sre.getServletRequest().setAttribute("startTime", startTime);
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - (long)sre.getServletRequest().getAttribute("startTime");

        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();

        String clientIP = sre.getServletRequest().getRemoteAddr();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        String queryString = request.getQueryString();
        String userAgent = request.getHeader("User-Agent");

        logger.info(String.format("Request Log: Time: %d ms, IP: %s, Method: %s, URI: %s, Query: %s, User-Agent: %s",
                elapsedTime, clientIP, method, requestURI, queryString, userAgent));
    }
}
/*<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd"
version="6.0">

</web-app>